﻿var bizCL = null;
$(document).ready(function() {
    $(window).load(function() {
        var queueSize = parseFloat($("#queuesize").val());
        var tmpFileSize = parseFloat($("#totalFSize").val());
        var lastFileID = null;
        var arrFiles = [];
        var tmpArrFile = {};
        $("#" + fileUpCtrl).uploadify({
            'swf': 'scripts/uploadify.swf',
            'buttonText': 'Browse Files',
            'uploader': 'uploadHandler.ashx',
            'folder': 'images/upload',
            'fileTypeDesc': 'Image Files',
            'fileTypeExts': '*.jpg;*.jpeg;*.gif;*.png;*.zip;*.rar;*.doc;*.docx;*.xls;*.xlsx;*.pdf;',
            'multi': false,
            'height': 18,
            'auto': false,
            'fileSizeLimit': '5MB',
            'onQueueComplete': function(data) {
                saveFiles(bizCL, arrFiles);
            },
            'onSelectError': function(file) {
                return false;
            },
            'onSelect': function(file) {
                queueSize++;
                $('#queuesize').val(queueSize);
                lastFileID = file.id;
            },
            'onUploadSuccess': function(file, data, response) {
                tmpArrFile = {
                    "FileName": data,
                    "FileSize": file.size,
                    "FileType": file.type
                }
                arrFiles.push(tmpArrFile);
            },
            'onDialogClose': function(queueData) {
                if ((parseFloat(queueData.queueSize) + tmpFileSize) > 5242880) {
                    var errMsg = "File exceeds 5MB limit:\nLast file in queue will not be added";
                    alert(errMsg);
                    $("#" + fileUpCtrl).uploadify('cancel', lastFileID);
                }
            },
            'onCancel': function(file) {
                var idxFile = file.index;
                arrFiles.splice(idxFile, 1);

                queueSize--;
                $('#queuesize').val(queueSize);
            }
        });
    });

    $('#' + Form1).submit(function(e) {
        e.preventDefault();
        saveRequest();
    });

    $('#cbDistributor').change(function() {
        $('#btnClearCust, #btnClearProd').click();
        $('#divApproval').html('');
        $('#spnMaxSteps').text();
    });

    $(".txtDatePick").datepicker({
        dateFormat: 'dd-mm-yy',
        changeMonth: true,
        changeYear: true
    });

    $('#txtDate1').change(function() {
        var dtStart = $(this);
        var dtEnd = $('#txtDate2');
        var valStart = dtStart.datepicker("getDate");
        var valEnd = dtEnd.datepicker("getDate");

        var tmpEnd;
        if (valStart > valEnd) {
            alert('Date End has been re-adjusted!');
            dtEnd.datepicker("setDate", valStart);
        }
    });

    $('#txtDate2').change(function() {
        var dtStart = $('#txtDate1');
        var dtEnd = $(this);
        var valStart = dtStart.datepicker("getDate");
        var valEnd = $(this).datepicker("getDate");

        if (valEnd < valStart) {
            alert('Can not set lower date than Date Start!');
            dtEnd.datepicker("setDate", valStart).blur();
        }
    });

    $('#cbChannel').change(function() {
        getRuleList();
    });

    $('#btnAddCustomer, #btnAddProduct').click(function() {
        var txtdiscval = $('#txtDiscount').val();
        var txtqtyval = $('#txtQuantity').val();

        var thisval = $(this).text();
        var show_mode = (thisval == 'Select Customer') ? 0 : 1;
        var dSelect = $('#cbDistributor');
        if (dSelect.val() != 0) {
            if (show_mode == 1) {
                if (typeof txtdiscval == 'undefined' || txtdiscval == '' || isNaN(txtdiscval) == true) {
                    alert('Discount must be filled!');
                    return false;
                } else if (typeof txtqtyval == 'undefined' || txtqtyval == '' || isNaN(txtqtyval) == true) {
                    alert('Quantity must be filled!');
                    return false;
                }
            }
            showDialog(show_mode, "");
        } else {
            alert('Please select distributor first!');
        }
    });

    $('#btnClearCust').click(function() {
        var preValue = $("#totalCust").text();
        if (!(preValue == '0' || preValue == 0)) {
            var tblBody = $('#tblCustomers > tbody');
            var clearContent = ' <tr>' +
            '<td colspan="5" style="padding:15px 0; text-align:center; width:753px; height:147px; ' +
            'border-bottom:1px solid #ccc;">Please select customer(s)</td></tr>';
            tblBody.html(clearContent);
            $('#totalCust').text("0");
        }
    });

    $('#btnClearProd').click(function() {
        var preValue = $("#totalProd").text();
        if (!(preValue == '0' || preValue == 0)) {
            var tblBody = $('#tblProducts > tbody');
            var clearContent = ' <tr>' +
            '<td colspan="5" style="padding:15px 0; text-align:center; width:753px; height:147px; ' +
            'border-bottom:1px solid #ccc;">Please select product(s)</td></tr>';
            tblBody.html(clearContent);
            $('#totalProd, #MaxDisc').text("0");
            maxDiscval();
        }
    });

    $('#ModalDialog').on('click', '#btnSearch', function() {
        var tmpval = $(this).prev().prev().val();
        if (typeof tmpval == 'undefined' || tmpval == '') {
            alert('Please type keywords!');
            return false;
        } else {
            var xndr = $(this).prev().text();
            var xmode = (xndr == 'cLst') ? 0 : 1;
            var sval = $(this).parent().children('#autocomplete1').val();
            var idds = $('#cbDistributor').val();
            getDataList(0, sval, xmode);
        }
    });

    $('#ModalDialog').on('keypress', '#autocomplete1', function(e) {
        if (e.keyCode == 13) {
            var thisval = $(this).val()
            if (typeof thisval == 'undefined' || thisval == '') {
                alert('Please type keywords!');
                return false;
            } else {
                var xndr = $(this).next().text();
                var xmode = (xndr == 'cLst') ? 0 : 1;
                var sval = $(this).val();
                getDataList(0, sval, xmode);
            }
        }
    });

    $('#ModalDialog').on('click', '.tRow', function(e, src) {
        var trgt = e.target.cellIndex;
        if (!trgt == 0) {
            $(this).children().find('input:checkbox').click();
        }
    });

    $('#ModalDialog').on('change', '.chkAdd', function(e) {
        var pTable = $(this).parentsUntil('#divModalWrap').eq(3);
        var pBody = pTable.children('tbody');
        var parentID = pTable.attr("id");
        var tblTarget = (parentID == 'tblCustomer') ? $('#tblCustomers > tbody') : $('#tblProducts > tbody');
        var lblTarget = (parentID == 'tblCustomer') ? $('#totalCust') : $('#totalProd');
        var iState = $(this).prop('checked');
        if (iState == true) {
            var thisval = $(this).val();
            var sData = [];
            sData.push(thisval);
            if (parentID == 'tblCustomer') {
                var txtIDAzi = $(this).closest('tr').children('td').eq(2).text();
                var txtCustName = $(this).closest('tr').children('td').eq(3).text();
                var txtAddr = $(this).closest('tr').children('td').eq(4).text();

                sData.push(txtIDAzi);
                sData.push(txtCustName);
                sData.push(txtAddr);
            } else {
                var txtProdName = $(this).closest('tr').children('td').eq(2).text();
                sData.push(txtProdName);
            }
            
            var tblRows = tblTarget.children('tr');
            var rowLength = tblRows.length;
            var tblCell = tblRows.children('td');
            if (rowLength <= 1) {
                var cLength = tblCell.length;
                if (cLength <= 1) {
                    tblTarget.html("");
                    insertData(tblTarget, sData, 0, 1);
                } else {
                    insertData(tblTarget, sData, rowLength);
                }
            } else {
                insertData(tblTarget, sData, rowLength);
            }
        } else {
            removeData(tblTarget, $(this).val(), 1);
        }
        lblTarget.text(tblTarget.children('tr').length);
        if (parentID == 'tblProduct') {
            maxDiscval();
        }
    });

    $('#ModalDialog').on('change', '#chkAll', function(e) {
        var iState = $(this).prop('checked');
        var tblBody = $(this).closest('tr').parent().next();
        var trLen = tblBody.children('tr').length;
        if (trLen > 0) {
            var tRows = tblBody.children('tr');
            for (var i = 0; i < trLen; i++) {
                var chkBoxes = tRows.eq(i).children('td').eq(0).children('input:checkbox');
                if (!(chkBoxes.prop('checked') == iState)) {
                    chkBoxes.click();
                }
            }
        }
    });

    $('#tblCustomers, #tblProducts').on('click', '.btnRemove', function(e) {
        var rowSrc = $(this).closest('tr');
        var rowIdx = rowSrc.index();
        var tbodySrc = rowSrc.parent();
        removeData(tbodySrc, rowIdx);
    });

    $('#tblProducts').on('change', '.txtDiskon', function() {
        maxDiscval();
    });

    $('#divApproval').on('change', '.cbAppList', function() {
        var thisval = $(this).val();
        var divParent = $('#divApproval');
        var divChild = divParent.children();
        var divChildLen = divChild.length;
        var thisIndex = $(this).parent().index();
        var nextIndex = thisIndex + 1;
        if (divChildLen > 1) {
            for (var idx = nextIndex; idx < divChildLen; idx++) {
                divChild.eq(idx).remove();
            }
        }
        if (!(typeof thisval == 'undefined' || thisval == '' || thisval == '0' || thisval == 0)) {
            getAppPersons(nextIndex, thisval);
        }
    });

    $('#txtDiscount, #txtQuantity').change(function(e) {
        var txtdiscval = $(this).val();
        if (typeof txtdiscval == 'undefined' || txtdiscval == '' || isNaN(txtdiscval) == true) {
            $(this).val('0');
        }
    });

    $(".btnDelFile").click(function() {
        var thisParent = $(this).parent();
        var fileName = $(this).prev().text();
        var ULSrc = thisParent.parent();
        var thisID = thisParent.prev().val();
        var sendData = {
            "ID": $("#txtIDCLOri").val(),
            "IDFile": thisID,
            "FileName": fileName,
            "PrevQueue": $("#queuesize").val(),
            "PrevSize": $("#totalFSize").val()
        };
        $.ajax({
            type: "POST",
            url: "EditRequest.aspx/DeleteFile",
            data: JSON.stringify(sendData),
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function(data) {
                var result = data.d;
                var ULLen = ULSrc.children('li').length;
                if (result[0] == 1) {
                    if (ULLen == 1) {
                        ULSrc.parent().remove();
                    } else {
                        thisParent.remove();
                    }
                    $("#totalFSize").val(result[2]);
                    $("#queuesize").val(result[3]);
                }
                alert(result[1]);
            },
            beforeSend: function(jqXHR, setting) {
                //
            },
            error: function(jqXHR, statusText, errorText) {
                alert(errorText);
            }
        });
        return false;
    });

});

function checkTableData(tableMode) {
    var tblName = null;
    var tableName = "";
    switch (tableMode) {
        case 0:
            tblName = $("#tblCustomers > tbody");
            tableName = "Customer List";
            break;
        case 1:
            tblName = $("#tblProducts > tbody");
            tableName = "Product List";
            break;
    }
    var custRowLen = tblName.children('tr').length;
    if (custRowLen <= 1) {
        var TDLen = tblName.children('tr').eq(0).children('td').length;
        if (TDLen > 1) {
            return true;
        } else {
            alert(tableName + " is required!");
            return false;
        }
    } else {
        return true;
    }
}
function checkFieldData(arrFields) {
    var result = true;
    $.each(arrFields, function(dataKey, dataVal) {
        if ((typeof dataVal == 'undefined' || dataVal == '' ||
            dataVal == '0' || dataVal == 0) && dataKey != "CustGroup") {
            var fieldName = "";
            switch (dataKey) {
                case "Distributor":
                    fieldName = "Distributor";
                    break;
                case "DiscountType":
                    fieldName = "Discount Type";
                    break;
                case "Channel":
                    fieldName = "Channel";
                    break;
                case "CLCustName":
                    fieldName = "CL Customer Name";
                    break;
                case "CustGroup":
                    fieldName = "Customer Group";
                    break;
                case "Reason":
                    fieldName = "Reason to give Discount";
                    break;
                case "DateStart":
                    fieldName = "Date Start";
                    break;
                case "DateEnd":
                    fieldName = "Date End";
                    break;
            }
            alert(fieldName + " is required!");
            result = false;
            return false;
        }
    });
    return result;
}
function checkAppData() {
    var result = true;

    var divApproval = $("#divApproval");
    var divChild = divApproval.children('div');
    var divLen = divChild.length;
    if (divLen > 0) {
        for (var idx = 0; idx < divLen; idx++) {
            var cbApp = divChild.eq(idx).children('.cbAppList');
            if (cbApp.val() == '0' || cbApp.val() == 0) {
                alert("Approval Process must be completed!");
                result = false;
                return false;
            }
        }
    } else {
        result = false;
    }
    return result;
}
function checkUpload() {
    var result = true;

    var olUp = $("#olDoc");
    var olChild = olUp.children('li');
    var olChildLen = olChild.length;

    if (olChildLen < 1) {
        var divUp = $("#divUpList");
        var divChild = divUp.children().eq(1).children();
        if (divChild.length < 1) {
            alert("Supporting file must be attached!");
            result = false;
        } else {
            result = true;
        }
    } else {
        result = true;
    }
    
    return result;
}
function mergeObjects(obj1, obj2) {
    var obj = {};
    for (var x in obj1) {
        if (obj1.hasOwnProperty(x)) {
            obj[x] = obj1[x];
        }
    }
    for (var y in obj2) {
        if (obj2.hasOwnProperty(y)) {
            obj[y] = obj2[y];
        }
    }
    return obj;
}
function saveRequest() {
    var _IDCL = $("#txtIDCLOri").val();
    var _Distributor = $("#cbDistributor").val();
    var _DiscountType = $("#cbDiscType").val();
    var _Channel = $("#cbChannel").val();
    var _CLCustName = $("#txtCLCustName").val();
    var _CustGroup = $("#txtCustGroup").val();
    var _Reason = $("#txtReason").val();
    var _DateStart = $("#txtDate1").val();
    var _DateEnd = $("#txtDate2").val();
    var _Discount = $("#txtDiscount").val();
    var _Quantity = $("#txtQuantity").val();
    var _ProductDivision = $("#txtProdDiv").val();

    var dataFields = {
        "IDCL": _IDCL, 
        "Distributor": _Distributor,
        "DiscountType": _DiscountType,
        "Channel": _Channel,
        "CLCustName": _CLCustName,
        "CustGroup": _CustGroup,
        "Reason": _Reason,
        "DateStart": _DateStart,
        "DateEnd": _DateEnd
    };

    var _PrevCL = $("#txtPrevCL").val();

    var divApproval = $("#divApproval");
    var divChild = divApproval.children('div');
    var divLen = divChild.length;
    var _CurrentApp = (divLen > 0) ? divChild.eq(0).children('.cbAppList').val() : "";
    var _NextApp = (divLen > 1) ? divChild.eq(1).children('.cbAppList').val() : "0";
    var _ApprovalStep = 1;
    var _ApprovalMax = divLen;

    var _RuleCtrl = $("#RuleCtrl").text();
    var _RuleVal = $("#RuleVal").text();
    var _RuleValExt = $("#RuleValExt").text();
    var extFields = {
        "ProductDivision": _ProductDivision,
        "PrevCL": _PrevCL,
        "RuleCtrl": _RuleCtrl,
        "RuleVal": _RuleVal,
        "RuleValExt": _RuleValExt,
        "CurrentStep": _CurrentApp,
        "NextStep": _NextApp,
        "ApprovalStep": _ApprovalStep,
        "ApprovalMax": _ApprovalMax
    };

    var sendData = mergeObjects(dataFields, extFields);
    if (checkFieldData(dataFields) == true && checkTableData(0) == true &&
        checkTableData(1) && checkAppData() == true && checkUpload() == true) {

        //process save
        $("#ModalDialog").showCZDialog({ "mode": "block" });
        $.ajax({
            type: "POST",
            url: 'EditRequest.aspx/SaveNewRequest',
            data: JSON.stringify(sendData),
            contentType: "application/json;charset=utf-8",
            datatype: "json",
            success: function(data) {
                var result = data.d;
                if (result[0] == 1) {
                    saveCustomers(_IDCL, _Distributor, _CustGroup, _ProductDivision);
                } else {
                    $("#ModalDialog").closeCZDialog();
                    alert(result[1]);
                }
            },
            error: function(jqXHR, statusText, errorText) {
                $("#ModalDialog").closeCZDialog();
                alert(errorText);
            }
        });
        return false;
    }
}
function saveCustomers(idCL, distributor, csGroup, ProductDivision) {
    var tblSrc = $("#tblCustomers > tbody");
    var tRows = tblSrc.children('tr');
    var rowLen = tRows.length;

    var csList = [];
    for (var idx = 0; idx < rowLen; idx++) {
        var _csID = tRows.eq(idx).children('td').eq(0).text();
        var _csIDAzi = tRows.eq(idx).children('td').eq(1).text();
        var _csName = tRows.eq(idx).children('td').eq(2).text();
        var _csAddr = tRows.eq(idx).children('td').eq(3).text();

        var csDetails = {
            "CSID": _csID,
            "CSIDAzi": _csIDAzi,
            "CSName": _csName,
            "CSAddress": _csAddr
        };
        csList.push(csDetails);
    }

    var sendData = {
        "ID": idCL,
        "Distributor": distributor,
        "CSGroup": csGroup,
        "CSList": csList
    };
    $.ajax({
        type: "POST",
        url: 'EditRequest.aspx/SaveCustomers',
        data: JSON.stringify(sendData),
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            var result = data.d;
            if (result == "success") {
                saveProducts(idCL, distributor, ProductDivision);
            } else {
                alert("Update New Request Failed!");
            }
        }
    });
    return false;
}
function saveProducts(idCL, distributor, ProductDivision) {
    var tblSrc = $("#tblProducts > tbody");
    var tRows = tblSrc.children('tr');
    var rowLen = tRows.length;
    
    var prodList = [];
    for (var idx = 0; idx < rowLen; idx++) {
        var _prodID = tRows.eq(idx).children('td').eq(0).text();
        var _prodName = tRows.eq(idx).children('td').eq(1).text();
        var _prodDisc = tRows.eq(idx).children('td').eq(2).find("input:text").val();
        var _prodQTY = tRows.eq(idx).children('td').eq(3).find("input:text").val();

        var prodDetails = {
            "ProdID": _prodID,
            "ProdName": _prodName,
            "ProdDisc": _prodDisc,
            "ProdQTY": _prodQTY
        };
        prodList.push(prodDetails);
    }
    var sendData = {
        "ID": idCL,
        "ProductDivision": ProductDivision,
        "Distributor": distributor,
        "ProductList": prodList
    };
    $.ajax({
        type: "POST",
        url: 'EditRequest.aspx/SaveProducts',
        data: JSON.stringify(sendData),
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            var result = data.d;
            if (result == "success") {
                //if success, save Approval
                saveApproval(idCL);
            } else {
                alert("Update New Request Failed!");
            }
        }
    });
    return false;
}
function saveApproval(idCL) {
    //This function will update approval list and send email
    var divSrc = $("#divApproval");
    var divChild = divSrc.children('.divAppList');
    var divLen = divChild.length;

    var appvList = [];
    for (var idx = 0; idx < divLen; idx++) {
        var step = idx + 1;
        var cStep = divChild.eq(idx).children('.cbAppList').val();
        var nStep = ((idx + 1) < divLen) ? divChild.eq((idx + 1)).children('.cbAppList').val() : '0';
        var appvDetails = {
            "StepNum": step,
            "CStep": cStep,
            "NStep": nStep
        }
        appvList.push(appvDetails);
    }
    var sendData = {
        "ID": idCL,
        "ApprovalList": appvList
    };

    $.ajax({
        type: "POST",
        url: 'EditRequest.aspx/SaveApprovals',
        data: JSON.stringify(sendData),
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            var result = data.d;
            if (result.Status == 1) {
                //if success, upload docs
                bizCL = idCL;
                submitFiles();
            }
        }
    });
    return false;
}
function submitFiles() {
    var queueval = $("#queuesize").val();
    if (queueval == 0) {
        alert('Supporting Document must be attached!');
    } else {
        var olUp = $("#olDoc");
        var olChild = olUp.children('li');
        var olChildLen = olChild.length;

        if (olChildLen < 1) {
            var divUp = $("#divUpList");
            var divChild = divUp.children().eq(1).children();
            if (divChild.length > 1) {
                $("#" + fileUpCtrl).uploadify('upload', '*');
            }
        } else {
            alert("Update Request Success!\nPlease check your email.");
            window.location.href = "Home.aspx";
        }
    }
}
function saveFiles(idCL, fileList) {
    var sendData = {
        "ID": idCL,
        "FileList": fileList
    };
    $.ajax({
        type: "POST",
        url: 'EditRequest.aspx/AttachFiles',
        data: JSON.stringify(sendData),
        contentType: "application/json;charset=utf-8",
        datatype: "json",
        success: function(data) {
            var result = data.d;
            //on success: redirect page
            alert(result.Message);
            window.location.href = result.Goto;
        }
    });
    return false;
}

// -- Function Non Upload
function getRuleList() {
    var channel = $('#cbChannel').val();
    var maxDisc = $('#MaxDisc').text();
    var strData = '{"RuleValue":"' + channel + '", "RuleValueExt":"' + maxDisc + '"}';
    $.ajax({
        type: "POST",
        url: "EditRequest.aspx/GetRuleList",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            $('#divApproval').html('');
            setCache(data.d);
        }
    });
    return false;
}

function setCache(data) {
    if (data.RuleExist == '1') {
        $('#RuleCtrl').text(data.RuleCtrl);
        $('#RuleVal').text(data.OptValue);
        $('#RuleValExt').text(data.OptValueExt);
        $('#FixDisc').text(data.FixDiscount);
        $('#MaxLayers').text(data.MaxSteps);
        
        var txtMax = '(Max: ' + data.MaxSteps + ')';
        $('#spnMaxSteps').text(txtMax).css("color", "green").prop("title", "Max Layers");
        insertAppList(0, data.AppList);
    } else {
        $('#RuleCtrl').text('');
        $('#RuleVal').text('');
        $('#RuleValExt').text('0');
        $('#FixDisc').text('0');
        $('#MaxLayers').text('0');
        $('#spnMaxSteps').text('(N / A)').css("color", "red").prop("title", "Not Available");

        $('#divApproval').html('');
    }
    checkFixDiscount();
}
function checkFixDiscount() {
    var fixDsc = parseInt($('#FixDisc').text());

    var tblSrc = $('#tblProducts > tbody');
    var tRow = tblSrc.children('tr');

    var idx = 0;
    var trLen = tRow.length;
    if (fixDsc == 1) {
        var FixedDiscout = $('#RuleValExt').text();
        $('#txtDiscount').text(FixedDiscout).prop("readonly", true);
        if (trLen <= 1) {
            var tdLen = tRow.children('td').length;
            if (tdLen > 1) {
                for (idx; idx < trLen; idx++) {
                    tRow.eq(idx).children('td').eq(3).children('.txtDiskon').val(FixedDiscout).prop("readonly", true);
                }
            }
        } else {
            for (idx; idx < trLen; idx++) {
                tRow.eq(idx).children('td').eq(3).children('.txtDiskon').val(FixedDiscout).prop("readonly", true);
            }
        }
    } else {
        $('#txtDiscount').prop("readonly", false);
        if (trLen <= 1) {
            var tdLen = tRow.children('td').length;
            if (tdLen > 1) {
                for (idx; idx < trLen; idx++) {
                    tRow.eq(idx).children('td').eq(3).children('.txtDiskon').prop("readonly", false);
                }
            }
        } else {
            for (idx; idx < trLen; idx++) {
                tRow.eq(idx).children('td').eq(3).children('.txtDiskon').prop("readonly", false);
            }
        }
    }
}
function createAppList(maxLayers) {
    var tmp = '<div class="divAppList">' +
    '<select name="cbAppList[]" class="cbAppList">' +
    '<option value="0">--- Select ---</option>' +
    '</select>' +
    '</div>';

    var maxAppLayers = parseInt(maxLayers);
    var divParent = $('#divApproval');
    var divChildLen = divParent.children().length;

    var cbList = '';
    var idx = divChildLen;
    for (idx; idx < maxAppLayers; idx++) {
        cbList += tmp;
    }
    divParent.html(cbList);
}
function getAppPersons(layerNum, currentApproval) {
    var ruleCtrl = $('#RuleCtrl').text();
    var ruleVal = $('#RuleVal').text();
    var ruleValExt = $('#RuleValExt').text();

    var nextLayer = parseInt(layerNum + 1);
    var strData = '{"RuleControl":"' + ruleCtrl + '", ';
    strData += '"RuleValue":"' + ruleVal + '", ';
    strData += '"RuleValueExt":"' + ruleValExt + '", ';
    strData += '"ApprovalLayer":' + nextLayer + ', ';
    strData += '"CurrentApproval":"' + currentApproval + '"}';
    $.ajax({
        type: "POST",
        url: "EditRequest.aspx/GetApprovalList",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            var dLen = data.d.length;
            var divParent = $('#divApproval');
            var divChild = divParent.children();
            var divChildLen = divChild.length;
            if (dLen > 0) {
                var isVisible = divChild.eq(layerNum).is(':visible');
                if (!isVisible) {
                    insertAppList(layerNum, data.d);
                } else {
                    fillAppList(layerNum, data.d);
                }
            } else {
                for (var idx = layerNum; idx < divChildLen; idx++) {
                    divChild.eq(idx).remove();
                }
                var cbval = divChild.eq((layerNum - 1)).children().val();
                if (cbval != '0' || cbval != 0) {
                    alert('End of Approval Layer');
                }
            }
        }
    });
    return false;
}
function insertAppList(layerIndex, content) {
    var tmp = '<div class="divAppList" style="display:none;">' +
    '<select name="cbAppList[]" class="cbAppList">' +
    '<option value="0">--- Select ---</option>' +
    '</select>' +
    '</div>';

    var divParent = $('#divApproval');
    divParent.append(tmp);
    fillAppList(layerIndex, content);
}

function fillAppList(layerIndex, content) {
    var divParent = $('#divApproval');
    var divChild = divParent.children().eq(layerIndex);
    var divTarget = divChild.children();

    var cLen = 0;
    if (!(typeof content == 'undefined' || content == '')) {
        var opt = '<option value="0">--- Select ---</option>';

        cLen = content.length;
        for (var idx = 0; idx < cLen; idx++) {
            var optKey = '<option value="' + content[idx].appKey + '">';
            var optVal = content[idx].appVal + '</option>';
            opt += optKey + optVal;
        }
        divTarget.html(opt);
        divChild.fadeIn(300);
    }
}
function maxDiscval() {
    var tblTarget = $('#tblProducts > tbody');
    var tRows = tblTarget.children('tr');
    var tRowsLen = tRows.length;

    if (tRowsLen > 0) {
        var tdLen = tRows.children('td').length;
        if (tdLen > 1) {
            var spnMaxDisc = $('#MaxDisc');
            var DiscVal = parseFloat(spnMaxDisc.text());
            var newDiscVal = 0;

            for (var idx = 0; idx < tRowsLen; idx++) {
                var tmpPrevDsc;
                var tmpCurrDsc;
                if (idx < 1) {
                    tmpPrevDsc = 0;
                } else {
                    tmpPrevDsc = tRows.eq((idx - 1)).children('td').find('input:text').val();
                }
                tmpCurrDsc = tRows.eq(idx).children('td').find('input:text').val();

                var prevDsc = parseFloat(tmpPrevDsc);
                var currDsc = parseFloat(tmpCurrDsc);
                if (currDsc > prevDsc) {
                    newDiscVal = currDsc;
                }
            }
            if (newDiscVal != DiscVal) {
                spnMaxDisc.text(newDiscVal);
                getRuleList();
            }
        } else {
            getRuleList();
        }
    } else {
        getRuleList();
    }
}
function removeData(srcTbody, rowIdxOrVal, removeMode) {
    var isProdChange = false;
    var remMode = (typeof removeMode == 'undefined' || removeMode == '') ? 0 : 1;
    var rowIndex = 0;

    var tblSrc = srcTbody.parent().attr("id");
    var rowSrc = srcTbody.children('tr');

    if (remMode == 0) {
        rowIndex = rowIdxOrVal;
    } else if (remMode == 1) {
        var newRowSrc = srcTbody.children('tr');
        var initRowLen = newRowSrc.length;
        for (i = 0; i < initRowLen; i++) {
            var currvals = newRowSrc.eq(i).children('td').eq(0).text();
            if (currvals == rowIdxOrVal) {
                rowIndex = i;
                break;
            }
        }
    }
    rowSrc.eq(rowIndex).remove();

    switch (tblSrc) {
        case 'tblCustomers':
            isProdChange = false;
            break;
        case 'tblProducts':
            isProdChange = true;
            break;
    }

    var rowLngth = (srcTbody.children('tr').length);
    if (rowLngth > 0) {
        var newTBody = srcTbody; //re-bind control
        var newTR = newTBody.children('tr');
        for (var idx = 0; idx < rowLngth; idx++) {
            var oddEven = ((idx % 2) == 1) ? 'even' : 'odd';
            newTR.eq(idx).attr('class', oddEven);
        }
        if (isProdChange == true) {
            maxDiscval();
        }
    } else {
        var txtNoData = '';
        switch (tblSrc) {
            case 'tblCustomers':
                txtNoData = 'Please select customer(s)';
                break;
            case 'tblProducts':
                $('#MaxDisc').text('0');
                txtNoData = 'Please select product(s)';
                break;
        }
        var zRow = '<tr><td colspan="5" style="padding:15px 0; text-align:center; width:753px; height:147px; border-bottom:1px solid #ccc;">';
        zRow += txtNoData;
        zRow += '</td></tr>';
        srcTbody.html(zRow);
    }
}
function insertData(tblTarget, sData, rowNum, firstRow) {
    var isFirstRow = (typeof firstRow == 'undefined' || firstRow == '') ? 0 : firstRow;
    var oddEven = '';
    var newRow = '';
    var isProdChange = false;
    var imgDel = '<img src="images/delete.png" class="btnRemove" alt="Remove" title="Remove" style="cursor:pointer;' +
        'border:0;height:14px;width:14px;" />';
    oddEven = ((rowNum % 2) == 0) ? ' class="odd"' : ' class="even"';
    switch (tblTarget.parent().attr("id")) {
        case 'tblCustomers':
            newRow = '<tr' + oddEven + '>' +
            '<td style="width:85px;">' + sData[0] + '</td>' +
            '<td style="width:85px;">' + sData[1] + '</td>' +
            '<td style="width:267px;">' + sData[2] + '</td>' +
            '<td style="width:258px;">' + sData[3] + '</td>' +
            '<td style="text-align:center;width:24px;">' + imgDel + '</td></tr>';

            isProdChange = false;
            break;
        case 'tblProducts':
            var tplDisc = $('#txtDiscount').val();
            var tplQty = $('#txtQuantity').val();
            var isReadonly = ($('#MaxDisc').text() == '1' || $('#MaxDisc').text() == 1) ? ' readonly="readonly"' : '';
            var fixDisc = ($('#MaxDisc').text() == '1' || $('#MaxDisc').text() == 1) ? $('#RuleValExt').text() : tplDisc;

            var extStyle1 = ' style="font-size:12px;width:72px;padding:0;margin:0;text-align:right;"';
            var extStyle2 = ' style="font-size:12px;width:72px;padding:0;margin:0;text-align:right;"';

            var extRow = '<td style="width:76px;">';
            extRow += '<input type="text" ' + isReadonly + ' name="txtDiskon[]" class="txtDiskon" value="' + fixDisc + '"' + extStyle1 + ' /></td>';
            extRow += '<td style="width:76px;"><input type="text" name="txtJuml[]" class="txtQty" value="' + tplQty + '" ' + extStyle2 + ' /></td>';
            extRow += '<td style="text-align:center;width:24px;">' + imgDel + '</td>';

            newRow = '<tr' + oddEven + '>' +
            '<td style="width:85px;">' + sData[0] + '</td>' +
            '<td style="width:458px;">' + sData[1] + '</td>' +
            extRow + '</tr>';

            isProdChange = true;
            break;
    }

    if (isFirstRow == 0) {
        tblTarget.append(newRow);
        tblTarget.children('tr').eq(rowNum).css('border-bottom', '1px solid #ccc');
    } else {
        tblTarget.html(newRow);
        tblTarget.children('tr').eq(0).css('border-bottom', '1px solid #ccc');
    }

    if (isProdChange == true) {
        maxDiscval();
    }
}
function getDataList(startIndex, searchKey, showMode) {
    var result = "";

    var idds = $('#cbDistributor').val();
    var searchID = (idds == '' || idds == '0') ? '' : idds;
    var searchName = (typeof searchKey == 'undefined' || searchKey == '') ? '' : searchKey;
    var startIdx = (typeof startIndex == 'undefined' || startIndex == '') ? 0 : parseInt(startIndex);

    var strData = '{"ID": "' + searchID + '"';
    strData += ', "Name": "' + searchName + '"';
    strData += ', "StartIndex": ' + startIdx;
    strData += ', "showMode": ' + showMode + '}';
    $.ajax({
        type: "POST",
        url: "NewRequest.aspx/ShowDataList",
        contentType: "application/json;charset=utf-8",
        data: strData,
        datatype: "json",
        success: function(data) {
            var findTbl = $('#ModalDialog').children().find('table > tbody');
            findTbl.html("");
            processData(showMode, data.d, findTbl);
        }
    });
    return false;
}
function isValExist(checkValue, showMode) {
    var result = -1;
    var proceedCheck = false;

    var tblSrc = (showMode == 0) ? $('#tblCustomers > tbody') : $('#tblProducts > tbody');
    var rows = tblSrc.children('tr');
    var rowLen = rows.length;
    if (rowLen <= 1) {
        var tdLen = rows.children('td').length;
        proceedCheck = (tdLen <= 1) ? false : true;
    } else {
        proceedCheck = true;
    }

    if (proceedCheck == true) {
        for (var idx = 0; idx < rowLen; idx++) {
            var currValues = rows.eq(idx).children('td').eq(0).text();
            if (currValues == checkValue) {
                result = idx;
                break;
            }
        }
    }
    return result;
}
function processData(showMode, data, tblBody) {
    var rowData = "";
    var noneText = 'Data not found';
    var noneColspan = 3;
    var noneWidth = (showMode == 0) ? 769 : 442; //this must be edited
    var noneStyle = ' colspan="' + noneColspan + '" ' +
            'style="padding:30px 10px; text-align:center; width:' + noneWidth + 'px;' +
            'border:0; color:Red;">';

    var totalChecked = 0;
    if (!(typeof data.Content == 'undefined' || data.Content == 'null')) {
        var dataLength = (data.Content).length;
        if (dataLength > 0) {
            var rawData = data.Content;

            var styleTD = ' style="table-layout:fixed;';

            var styleTD1 = ' style="table-layout:fixed;width:29px;text-align:center;"';
            var styleTD2 = ' style="table-layout:fixed;width:124px;"';
            var styleTD3 = ' style="table-layout:fixed;width:287px;"';

            var startTD1 = '<td' + styleTD1 + '>';
            var startTD2 = '<td' + styleTD2 + '>';
            var startTD3 = '<td' + styleTD3 + '>';
            var endTD = '</td>';

            var startTR = '<tr class="tRow ';
            var endTR = '</tr>';

            var styleTR = ' style="cursor:pointer;';
            var hoverIn = ' onmouseover="this.style.background=\'#ccc\';"';
            var hoverOut = ' onmouseout="this.style.background=\'\';" ';
            var eventHover = hoverIn + hoverOut;

            var currentIdx = parseInt(data.ActivePage);
            var cIdx = (currentIdx < 1) ? 1 : currentIdx;
            var idXs = 0;
            for (var idx = 0; idx < dataLength; idx++) {
                idXs++;

                if ((isValExist(rawData[idx].ID, showMode)) > -1) {
                    chkState = ' checked="checked"';
                    totalChecked++;
                } else {
                    chkState = '';
                }
                var chkIdx = (cIdx * 15) - (15 - idx);
                var isOddorEven = (idx % 2 == 0) ? 'odd cls' + showMode : 'even cls' + showMode;
                var isLastChild = (idx == (dataLength - 1)) ? 'border-bottom:1px solid #ccc;' : '';

                var rows = startTR + isOddorEven + '"' + styleTR + isLastChild + '"' + eventHover + '>';
                rows += startTD1 + '<input type="checkbox" class="chkAdd" name="chk[]" value="' + rawData[idx].ID + '"' + chkState + ' />' + endTD;

                if (showMode == 0) {
                    rows += '<td' + styleTD + 'width:88px;">' + rawData[idx].ID + '</td>';
                    rows += '<td' + styleTD + 'width:88px;">' + rawData[idx].IDAzi + '</td>';
                    rows += '<td' + styleTD + 'width:244px;">' + rawData[idx].Name + '</td>';
                    rows += '<td' + styleTD + 'width:287px;">' + rawData[idx].Address + '</td>';
                } else {
                    rows += startTD2 + rawData[idx].ID + endTD;
                    rows += startTD3 + rawData[idx].Name + endTD;
                    rows += endTR;
                }

                rowData += rows;
            }
            if (totalChecked == dataLength) {
                $('#chkAll').prop('checked', true);
            } else {
                $('#chkAll').prop('checked', false);
            }

            // Populate Pager -----------------------------------
            var tmpCtrl = $('#ModalDialog').children().find('#autocomplete1');
            var srchval = tmpCtrl.val();

            var popPrev = parseInt(data.PrevPage);
            if (popPrev > 0) {
                $('#popPrev').attr(
                    'onclick', 'getDataList(' + popPrev + ',"' + srchval + '",' + showMode + ');'
                ).css('display', 'block');
            } else {
                $('#popPrev').css('display', 'none');
            }

            var popNext = parseInt(data.NextPage);
            if (popNext > 0) {
                $('#popNext').attr(
                    'onclick', 'getDataList(' + popNext + ',"' + srchval + '",' + showMode + ');'
                ).css('display', 'block');
            } else {
                $('#popNext').css('display', 'none');
            }

            var popIndex = parseInt(data.ActivePage);
            var totalPages = parseInt(data.TotalPages);
            if (totalPages > 1) {
                if (popIndex > 0) {
                    $('#popIndex').text(popIndex + ' / ' + totalPages).css('display', 'block');
                } else {
                    $('#popIndex').css('display', 'none');
                }
            }
        } else {
            rowData = '<tr><td' + noneStyle + noneText + '</td></tr>';
            $('#popNext, #popPrev, #popIndex').css('display', 'none');
        }
    } else {
        rowData = '<tr><td' + noneStyle + noneText + '</td></tr>';
        $('#popNext, #popPrev, #popIndex').css('display', 'none');
    }
    tblBody.html(rowData);
}
function showDialog(showMode, content) {
    var result = "";

    var sender = (showMode == 0) ? "cLst" : "pLst";
    var tblID = (showMode == 0) ? "tblCustomer" : "tblProduct";
    var chkID = (showMode == 0) ? "chkCustomer" : "chkProduct";
    var colH1 = (showMode == 0) ? "Customer ID" : "Product ID";
    var colH2 = (showMode == 0) ? "Customer Name" : "Product Name";

    var wSearch = (showMode == 0) ? "675px" : "380px";
    var search = "<div style='margin:5px 0;'>" +
    "   <input id='autocomplete1' type='text' placeholder='Type & Enter' value='' style='width:" + wSearch + ";' />" +
    "   <span id='spnSender' style='display:none;'>" + sender + "</span>" +
    "   <div id='btnSearch' class='btnSmall'>Search</div>" +
    "</div>";
    var tbl1 = "<table id='" + tblID + "' class='tblstyle' style='border:0; width:100%;'>" +
            "<thead style='display:block;'>";

    if (showMode == 0) {
        tbl1 += "   <tr>";
        tbl1 += "       <th rowspan='2' style='table-layout: fixed; width:25px; text-align:center;'>";
        tbl1 += "       <input type='checkbox' id='chkAll' /></th>";
        tbl1 += "       <th colspan='2'>Customer ID</th>";
        tbl1 += "       <th rowspan='2' style='table-layout:fixed; width:240px;'>Customer Name</th>";
        tbl1 += "       <th rowspan='2' style='table-layout:fixed; width:300px;'>Address</th>";
        tbl1 += "   </tr>";
        tbl1 += "   <tr>";
        tbl1 += "       <th style='table-layout: fixed; width:84px;'>Distributor</th>";
        tbl1 += "       <th style='table-layout: fixed; width:84px;'>AZI</th>";
        tbl1 += "   </tr>";
    } else {
        tbl1 += "   <tr>";
        tbl1 += "       <th style='table-layout: fixed; width:25px; text-align:center;'>";
        tbl1 += "       <input type='checkbox' id='chkAll' /></th>" +
        "       <th style='table-layout: fixed; width:120px; text-align:center;'>Product ID</th>" +
        "       <th style='table-layout: fixed; width:300px; text-align:center;'>Product Name</th>" +
        "   </tr>";
    }
    tbl1 += "</thead>";
    tbl1 += "<tbody style='display:block; height:331px; overflow-y:scroll;'>";
    var tbl2 = "</tbody></table>";
    var noDisplay = 'display:none;';
    var pager = '<div id="modal-footer"><div id="btnClosePop" class="btnSmall fl_right" title="Close">Close</div><div id="modal-footer-sub">' +
        '<img src="images/prev.png" id="popPrev" alt="Previous" title="Previous" style="' + noDisplay + '" />' +
        '<div id="popIndex" class="fl_left" title="Page" style="' + noDisplay + '">1</div>' +
        '<img src="images/next.png" id="popNext" alt="Next" title="Next" style="' + noDisplay + '" />' +
        '<div class="cl_both"></div>' +
        '</div><div class="cl_both"></div></div>';

    var noneText = 'Please type keywords in search box';
    var noneColspan = (showMode == 0) ? 5 : 3;
    var noneWidth = (showMode == 0) ? 769 : 442;
    var noneStyle = ' colspan="' + noneColspan + '" ' +
            'style="padding:30px 10px; text-align:center; width:' + noneWidth + 'px;' +
            'border:0; color:Red;">';

    if (typeof content == 'undefined' || content == '') {
        content = '<tr><td' + noneStyle + noneText + '</td></tr>';
        $('#popNext, #popPrev, #popIndex').css('display', 'none');
    }
    var popWidth = (showMode == 0) ? 811 : 501;
    var popHeight = (showMode == 0) ? 498 : 476;
    result = search + tbl1 + content + tbl2 + pager;
    $("#ModalDialog").html(result).showCZDialog({
        width: popWidth, height: popHeight, closeButton: '#btnClosePop'
    });
}